<template>
  <div class="add-product-wrapper">
      <el-form ref="productRef" :model="form" :rules="rules" label-width="80px" class="demo-form-inline">
        <el-card class="box-card" style="margin: 20px 20px; font-size: 14px">
          <template v-slot:header>
            <div class="clearfix">
              <span>基本信息</span>
            </div>
          </template>
          <el-form-item label="商品编码" prop="outProductId">
            <el-input v-model="form.outProductId" placeholder="请输入商品编码" />
          </el-form-item>
          <el-form-item label="标题" prop="name">
            <el-input v-model="form.name" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="品牌" prop="brandId">
            <brand-select v-model="form.brandId" :value="form.brandId"></brand-select>
            <!--            <el-input v-model="form.brandId" placeholder="请输入品牌" />-->
          </el-form-item>
          <el-form-item label="分类" prop="categoryId">
<!--            <el-input v-model="form.categoryId" placeholder="请输入类型" />-->
<!--            <product-category-tree-select-->
<!--              v-model="form.categoryId"-->
<!--              :value="form.categoryId"-->
<!--              :props="{ value: 'id', label: 'name', children: 'children' }"-->
<!--              value-key="id"-->
<!--              placeholder="请选择上级类目"-->
<!--              check-strictly-->
<!--            />-->
            <product-category-cascader
              v-model="form.categoryId"
              :value="form.categoryId"
              placeholder="请选择上级类目"
              check-strictly
              @change="categoryChange"
            />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="form.sort" placeholder="请输入排序" />
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input v-model="form.price" placeholder="请输入价格" />
          </el-form-item>
          <el-form-item label="单位" prop="unit">
            <el-input v-model="form.unit" placeholder="请输入单位" clearable/>
          </el-form-item>
          <el-form-item label="商品重量" prop="weight">
            <el-input v-model="form.weight" placeholder="请输入商品重量，默认为克"  />
          </el-form-item>
          <el-form-item label="上架状态" prop="publishStatus">
            <el-radio-group v-model="form.publishStatus">
              <el-radio
                v-for="dict in pms_publish_status"
                :key="dict.value"
                :label="parseInt(dict.value)"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-card>

        <el-card class="box-card" style="margin: 20px 20px; font-size: 14px">
          <template v-slot:header>
            <div class="clearfix">
              <span>产品图片</span>
            </div>
          </template>
          <el-form-item label="主图" prop="pic">
            <image-upload v-model="form.pic" :limit="1"/>
          </el-form-item>
          <el-form-item label="轮播图" prop="albumPics">
            <image-upload v-model="form.albumPics"/>
          </el-form-item>
        </el-card>


        <el-card style="margin: 20px 20px; font-size: 14px">
          <template v-slot:header>
            <div class="clearfix">
              <span>产品规格</span>
            </div>
          </template>
          <el-form-item label="规格类型">
            <div class="sku-wrapper">
              <div class="sku_sorts">
                <div class="sku_sort" v-for="(s, idx0) in productAttr" :key="s.name">
                  <div class="label flex-center">
                    <div class="flex-one" style="width: 70%">
<!--                      <dict-select v-model="s.name" prop-name="sku_sort_list" value-prop="label"></dict-select>-->
                      <el-select v-model="s.name" clearable>
                        <el-option
                          v-for="item in sku_sort_list"
                          :key="item.value"
                          :label="item.label"
                          :value="item.label"
                        >
                        </el-option>
                      </el-select>
                      <a style="color: red;position: absolute; right: 18px;" @click="deleteSkuSort(idx0)">删除规格类型</a>
                    </div>

                  </div>
                  <div class="values" v-if="s.name">
                    <div class="value" v-for="(it2, idx1) in s.options" :key="idx1">
                      <el-input :value="it2.name" @input="changeName(s, idx1, $event)" placeholder="请输入规格名称"></el-input>
                      <a style="color: red; width: 100px; margin-left: 20px;" @click="deleteOption(s, idx1)"
                         v-if="idx1 < s.options.length - 1 || (s.options.length === maxOptionNum &amp;&amp; idx1 === 3)" >删除</a>
                    </div>
                  </div>
                </div>
              </div>
              <el-button v-if="productAttr.length < 2" @click="addSkuSort">+添加规格类型</el-button>
            </div>
          </el-form-item>
          <el-form-item label="规格信息">
            <el-button @click="refreshSku()" class="mb20">刷新列表</el-button>
            <el-table :data="form.skuList" :max-height="400">
              <el-table-column v-for="s in skuAttr" :label="s.name" :key="s.name" :prop="s.name"></el-table-column>
              <el-table-column label="展示图片">
                <template v-slot="{ row }">
                  <image-upload  v-model="row.pic" :limit="1" :is-show-tip="false"  />
<!--                  <oss-image-upload class="img-upload-mini" v-model="row.pic" :limit="1" :is-show-tip="false"></oss-image-upload>-->
                </template>
              </el-table-column>
              <el-table-column label="销售价格" >
                <template v-slot="{ row,$index }">
                  <el-form-item
                    :rules="{ required: true, message: '请填写价格', trigger: 'blur' }"
                    :prop="'skuList['+$index+'].price'">
                    <el-input v-model="row.price"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="库存">
                <template v-slot="{ row, $index }">
                  <el-input v-model="row.stock" type="number"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="编码">
                <template v-slot="{ row }">
                  <el-form-item>
                    <el-input v-model="row.outSkuId"></el-input>
                    <el-input v-model="row.spData" v-show="false"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-card>

        <el-card class="box-card" style="margin: 20px 20px; font-size: 14px">
          <template v-slot:header>
            <div class="clearfix">
              <span>详情页</span>
            </div>
          </template>
          <el-form-item label="移动端">
            <editor v-model="form.detailMobileHtml" :min-height="192"/>
          </el-form-item>
          <el-form-item label="PC端">
            <editor v-model="form.detailHtml" :min-height="192"/>
          </el-form-item>
        </el-card>
        <el-form-item>
          <div class="dialog-footer">
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-form-item>

      </el-form>
  </div>
</template>

<script setup name="AddProduct">
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/pms/product";
import {useRouter, useRoute} from "vue-router";
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const { pms_publish_status } = proxy.useDict('pms_publish_status');
const { sku_sort_list } = proxy.useDict('sku_sort_list');


const productList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const productAttr = ref([]);
const maxOptionNum = 44;
const skuAttr = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productSnapshotId: undefined,
    brandId: undefined,
    categoryId: undefined,
    outProductId: undefined,
    name: undefined,
    publishStatus: 0,
    sort: 1000,
    price: undefined,
    unit: undefined,
    weight: undefined,
    detailHtml: undefined,
    detailMobileHtml: undefined,
    brandName: undefined,
    productCategoryName: undefined,
    productAttr: undefined,
    skuList: []
  },
  rules: {
    id: [
      { required: true, message: "ID不能为空", trigger: "blur" }
    ],
    productSnapshotId: [
      { required: true, message: "product_snapshot_id不能为空", trigger: "blur" }
    ],
    brandId: [
      { required: true, message: "品牌不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "类型不能为空", trigger: "blur" }
    ],
    outProductId: [
      { required: true, message: "商品编码不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "请输入商品名称", trigger: "blur" }
    ],
    pic: [
      { required: true, message: "主图不能为空", trigger: "blur" }
    ],
    albumPics: [
      { required: true, message: "画册图片，连产品图片限制为5张，以逗号分割不能为空", trigger: "blur" }
    ],
    publishStatus: [
      { required: true, message: "上架状态：0->下架；1->上架不能为空", trigger: "change" }
    ],
    sort: [
      { required: true, message: "排序不能为空", trigger: "blur" }
    ],
    // price: [
    //   { required: true, message: "价格不能为空", trigger: "blur" }
    // ],
    unit: [
      { required: true, message: "单位不能为空", trigger: "blur" }
    ],
    weight: [
      { required: true, message: "商品重量，默认为克不能为空", trigger: "blur" }
    ],
    detailHtml: [
      { required: true, message: "产品详情网页内容不能为空", trigger: "blur" }
    ],
    detailMobileHtml: [
      { required: true, message: "移动端网页详情不能为空", trigger: "blur" }
    ],
    // brandName: [
    //   { required: true, message: "品牌名称不能为空", trigger: "blur" }
    // ],
    // productCategoryName: [
    //   { required: true, message: "商品分类名称不能为空", trigger: "blur" }
    // ],
    productAttr: [
      { required: true, message: "商品销售属性，json格式不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);


// 取消按钮
function cancel() {
  const obj = { path: "/pms/products", query: { t: Date.now(), pageNum: route.query.pageNum} };
  proxy.$tab.closeOpenPage(obj);
}

// 表单重置
function reset() {
  form.value = {
    id: undefined,
    productSnapshotId: undefined,
    brandId: undefined,
    categoryId: undefined,
    outProductId: undefined,
    name: undefined,
    pic: undefined,
    albumPics: undefined,
    publishStatus: undefined,
    sort: undefined,
    price: undefined,
    unit: undefined,
    weight: undefined,
    detailHtml: undefined,
    detailMobileHtml: undefined,
    brandName: undefined,
    productCategoryName: undefined,
    createBy: undefined,
    createTime: undefined,
    updateBy: undefined,
    updateTime: undefined,
    productAttr: undefined
  };
  proxy.resetForm("productRef");
}



/** 提交按钮 */
function submitForm() {
  proxy.$refs["productRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      // if(albumPics.value){
      //   form.value.albumPics = albumPics.value.toString()
      // }
      if(form.value.categoryId && Array.isArray(form.value.categoryId)){
        form.value.categoryId = form.value.categoryId.pop()
      }
      //商品价格没填时取sku的最低价
      if (!form.value.price){
        form.value.price = Math.min.apply(Math, form.value.skuList.map(it => it.price))
      }
      if (form.value.id != null) {
        updateProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          cancel()
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          cancel()
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }else {
      proxy.$modal.msgError("表单校验未通过，请重新检查提交内容");
    }
  });
}


function changeName(s, idx, val) {
  s.options[idx].name = val;
  if (s.options.length - 1 !== idx || s.options.length >= maxOptionNum) {
    return
  }
  s.options.push({name: null})
}

function addSkuSort() {
  productAttr.value.push({
    name: null,
    options: [{name: null}]
  })
}
function deleteSkuSort(idx) {
  productAttr.value.splice(idx);
}
function deleteOption(s, idx) {
  s.options.splice(idx, 1);
}

function refreshSku(){
  let skus = [];
  let skuMap = new Map()
  skuAttr.value=[...productAttr.value]
  if(form.value.skuList){
    form.value.skuList.forEach(sku=>{
      skuMap.set(sku.spData,sku)
    })
  }
  productAttr.value.forEach((attr, index) => {
    const attrSku = [];
    attr.options.forEach((option) => {
      if (!option.name) {
        return
      }
      if (index === 0) {
        attrSku.push({[attr.name]: option.name});
      } else {
        skus.forEach(it3 => {
          attrSku.push({...it3, [attr.name]: option.name })
        })
      }
    })
    skus = attrSku;
  })
  skus.forEach(it => {
    if(it){
      it.spData=JSON.stringify(it)
    }
  })
  skus.forEach(it => {
    let sku = skuMap.get(it.spData);
    if(sku){
      it.outSkuId = sku.outSkuId;
      it.price = sku.price;
      it.pic = sku.pic;
      it.stock = sku.stock;
      it.id = sku.id
    }else{
      it.outSkuId = null;
      it.price = 0;
      it.pic = null;
      it.stock = 0;
      it.id = null
    }

  })
  form.value.productAttr = JSON.stringify(productAttr.value)
  form.value.skuList = skus
}

function getProductInfo(){
  const tableId =  route.query.id;
  if (tableId) {
    // 获取表详细信息
    getProduct(tableId).then(response => {
      loading.value = false;
      form.value = response.data;
      open.value = true;
      title.value = "修改商品信息";
      if(form.value.productAttr){
        productAttr.value =JSON.parse(form.value.productAttr)
      }
      refreshSku()
    });
  }
}

function categoryChange(value, nodes){
  form.value.categoryId = value;
  if(Array.isArray(nodes)){
    form.value.productCategoryName=nodes.join(",")
  }else{
    form.value.productCategoryName=undefined
  }
  console.log(value, form.value.productCategoryName)
}

getProductInfo();
</script>

<style scoped lang="scss">
.add-product-wrapper{
  padding: 12px;

}

.add-product-wrapper .content{
  margin: 0 auto;
  width: 75%;
  min-width: 800px;
}
.add-product-wrapper .sku-wrapper{
  width: 100%;
  min-width: 800px;
  background-color: #f7f8fa;
  padding: 12px;
}

.sku-wrapper .sku_sorts .sku_sort{
  background-color: white;
    margin-bottom: 12px;
}

.sku_sort .label{
  padding: 8px;
}

.sku_sort .values{
  padding: 8px 0 0 8px;
  border-top: 1px solid #DCDFE6;
  display: flex;
  flex-wrap: wrap;
  .value {
    padding: 0 32px 8px 0;
    width: 200px!important;
    display: flex;
    align-items: center;
  }
}

</style>
